package com.jfire.json.serializer;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.jfire.baseutil.collection.ObjectCollect;
import com.jfire.baseutil.collection.StringCache;
import com.jfire.json.JsonArray;
import com.jfire.json.field.JsonField;
import com.jfire.json.util.JsonConfig;
import com.jfire.json.util.JsonSerializer;

public class CollectionSerializer implements JsonSerializer
{
    
    @Override
    public Object transToJsonvalue(Object src, ObjectCollect collect)
    {
        JsonArray jsonArray = new JsonArray();
        for (Object each : (Collection<?>) src)
        {
            if (each != null)
            {
                jsonArray.add(JsonConfig.getSerializer(each.getClass()).transToJsonvalue(each, collect));
            }
        }
        return jsonArray;
    }
    
    @Override
    public void setJsonFields(JsonField[] jsonFields)
    {
        
    }
    
    @Override
    public void writeToString(StringCache cache, Object value, ObjectCollect collect)
    {
        cache.append('[', 10);
        for (Object each : (Collection<?>) value)
        {
            if (each != null)
            {
                JsonConfig.getSerializer(each.getClass()).writeToString(cache, each, collect);
                cache.append(',');
            }
        }
        if (cache.isCommaLast())
        {
            cache.deleteLast();
        }
        cache.append(']');
        
    }
    
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Object toBean(Object value, Type type)
    {
        List list = null;
        if (ArrayList.class.isAssignableFrom((Class<?>) ((ParameterizedType) type).getRawType()))
        {
            list = new ArrayList<>();
        }
        Type paramType = ((ParameterizedType) type).getActualTypeArguments()[0];
        JsonSerializer valueSerializer = null;
        if (paramType instanceof ParameterizedType)
        {
            valueSerializer = JsonConfig.getSerializer((Class<?>) ((ParameterizedType) paramType).getRawType());
        }
        else
        {
            valueSerializer = JsonConfig.getSerializer((Class<?>) paramType);
        }
        for (Object each : (JsonArray) value)
        {
            list.add(valueSerializer.toBean(each, paramType));
        }
        return list;
    }
}
